<?php

/**
 * Zend_Config with caching
 * @author greenogre <ogre.green@gmail.com>
 * @since 17.05.2012
 * @copyright 2012. greenogre
 * @licence LGPL
 */
class Green_Config {

    /**
     * @var Zend_Cache_Core
     */
    private static $_configCache;

    /**
     * @static
     * @param $file
     * @param null|Zend_Cache_Core $configCache
     * @return Zend_Config_Ini
     */
    public static function getConfig($file, Zend_Cache_Core $configCache = null) {
        self::$_configCache = $configCache;
        return self::_loadConfig($file);
    }

    /**
     * @static
     * @return string
     */
    protected static function getEnvironment() {
        return APPLICATION_ENV;
    }

    /**
     * @static
     * @param $file
     * @return string
     */
    protected static function _cacheId($file) {
        return md5($file . '_' . self::getEnvironment());
    }

    /**
     * @static
     * @param $file
     * @return Zend_Config_Ini
     */
    protected static function _loadConfigFromIni($file) {
        return new Zend_Config_Ini($file, APPLICATION_ENV);
    }

    /**
     * @static
     * @param $file
     * @return false|mixed|Zend_Config_Ini
     */
    protected static function _loadConfig($file)
    {
        $suffix = strtolower(pathinfo($file, PATHINFO_EXTENSION));
        if (
            self::$_configCache === null 
            || $suffix == 'php' 
            || $suffix == 'inc'
        ) { //No need for caching those
            return self::_loadConfigFromIni($file);
        }

        $configMTime = filemtime($file);
        
        $cacheId = self::_cacheId($file);
        $cacheLastMTime = self::$_configCache->test($cacheId);
        
        if (
            $cacheLastMTime !== false 
            && $configMTime < $cacheLastMTime
        ) { //Valid cache?
            return self::$_configCache->load($cacheId, true);
        } else {
            $config = self::_loadConfigFromIni($file);
            self::$_configCache->save($config, $cacheId, array(), null);

            return $config;
        }
    }    
}
